<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="elements"
        @submit="handleSearch"
        @reset="handleReset"
      >
        <Button icon="add" type="plain" @click="handleAdd">新增</Button>
        <Button
          icon="icon-xiazai"
          type="hollow"
          :btn-loading="xzLoading"
          @click="handleDealExcel(1)"
          >下载模板</Button
        >
        <el-upload
          class="upload-demo"
          action
          accept=".xls, .xlsx"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handlechange"
        >
          <Button class="buttons" type="hollow" icon="icon-daoru" :btn-loading="drLoading"
            >导入</Button
          >
        </el-upload>
        <Button
          type="hollow"
          icon="icon-daochu1"
          :btn-loading="dcLoading"
          @click="handleDealExcel(2)"
          >导出</Button
        >
      </FilterForm>
    </Container>
    <Container height="fill">
      <div class="wraper">
        <Table
          :index="true"
          :columns="tableColumns"
          :loading="tableLoading"
          :data="tableData"
          :pagination="{
            total: total,
            current: currentPage,
            pageSize: pageSize,
          }"
          @paginationChange="pageChange"
        >
          <template #status="{ row }">
            <el-switch
              v-model="row.status"
              active-color="#2178FB"
              :active-value="1"
              :inactive-value="0"
              @change="handleSwitch(row)"
            />
          </template>
          <template #caozuo="{ row }">
            <Tooltip
              content="查看数据项"
              icon="icon-chakan"
              @click="handleDataItem(row)"
            />
            <Tooltip content="编辑" icon="edit" @click="handleEdit(row)" />
            <Tooltip content="删除" icon="delete" @click="handleDelete(row)" />
          </template>
        </Table>
      </div>
      <!-- 新增、编辑 -->
      <Drawer
        ref="drawerRef"
        :title="title"
        :visible.sync="showDrawer"
        width="420px"
        :footer-btns="[
          {
            text: '确认',
            type: 'primary',
            loading: qrLoading,
            trigger: 'submit',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @submit="handleSubmit"
        @cancel="showDrawer = false"
      >
        <el-form
          v-if="showDrawer"
          ref="drawerForm"
          :model="drawerForm"
          :rules="drawerRules"
          label-width="120px"
          size="mini"
          class="demo-drawerForm"
        >
          <el-form-item label="字典名称：" prop="name">
            <el-input
              v-model.trim="drawerForm.name"
              placeholder="请输入"
              maxlength="20"
              clearable
            />
          </el-form-item>
          <el-form-item label="字典编码：" prop="code">
            <el-input
              v-model.trim="drawerForm.code"
              placeholder="请输入"
              maxlength="20"
              :disabled="btnType === 2"
              clearable
            />
          </el-form-item>
          <!-- <el-form-item label="数据来源：" prop="source">
            <el-select
              v-model="drawerForm.source"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in $getDataSource()"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="是否启用：">
            <el-switch
              v-model="drawerForm.status"
              :width="50"
              active-color="#2178FB"
              :active-value="'1'"
              :inactive-value="'0'"
            />
          </el-form-item>
          <el-form-item label="备注：">
            <el-input
              v-model.trim="drawerForm.description"
              type="textarea"
              placeholder="请输入"
              :rows="5"
              maxlength="50"
              clearable
            />
          </el-form-item>
        </el-form>
      </Drawer>
      <!-- 字典数据项 -->
      <FullPage
        :visible.sync="isShow"
        :show-footer="false"
        @handleFullClose="handleRefreshChange"
      >
        <template #header>
          <div style="font-weight: 700; color: #2165f9; margin-top: 5px">
            字典数据项
          </div>
        </template>
        <template #content>
          <DictionaryItem
            v-if="isShow"
            ref="addAndEdit"
            :current="currentRow"
          />
        </template>
      </FullPage>
    </Container>
  </ContainerGroup>
</template>
<script>
import {
  listSysDictByPage,
  saveOrUpdateDict,
  deleteDict,
  getExport,
  importExcel,
  updateDictStatus
} from "@/api/dictionary";
import DictionaryItem from "./dictionaryItem";
export default {
  components: {
    DictionaryItem,
  },
  data() {
    return {
      dcLoading: false,
      xzLoading: false,
      qrLoading: false,
      btnType: 1,
      isShow: false,
      optionList: [],
      drawerForm: {
        code: "",
        description: "",
        name: "",
        // source: "",
        status: "1",
      },
      drawerRules: {
        name: [{ required: true, message: "请输入字典名称", trigger: "blur" }],
        code: [{ required: true, message: "请输入字典编码", trigger: "blur" }],
        // source: [
        //   { required: true, message: "请选择数据来源", trigger: "change" },
        // ],
      },
      darawerLoading: false,
      showDrawer: false,
      title: "",
      fileList: [],
      importLoading: false,
      tableColumns: [
        {
          title: "字典名称",
          dataIndex: "name",
        },
        {
          title: "字典编码",
          dataIndex: "code",
        },
        // {
        //   title: "数据来源",
        //   dataIndex: "source",
        // },
        {
          title: "是否启用",
          dataIndex: "status",
          type: "otherTag",
        },
        {
          title: "备注",
          dataIndex: "description",
        },
        {
          title: "操作",
          dataIndex: "caozuo",
          type: "otherTag",
          width: 160,
        },
      ],
      total: 0,
      pageSize: 100,
      currentPage: 1,
      tableLoading: false,
      tableData: [],
      newCondition: {},
      elements: [
        {
          label: "综合搜索",
          type: "input",
          key: "nameOrCode",
          value: "",
          placeholder: "请输入字典名称或编码",
          width: 200,
        },
        {
          key: "status",
          label: "是否启用",
          type: "select",
          hideSelectAll: true,
          options: [
            {
              label: "是",
              value: "1",
            },
            {
              label: "否",
              value: "0",
            },
          ],
          value: "",
        },
      ],
      currentRow: {},
      drLoading: false,
    };
  },
  created() {},
  methods: {
    handleDealExcel(type) {
      if (type === 1) {
        this.xzLoading = true;
        getExport({
          type: 0,
        }).then((res) => {
          this.xzLoading = false;
          this.$utils.downloadFileFun(res, "字典管理.xls");
        });
      } else if (type === 2) {
        // 导出字典
        const params = {
          type: 1,
        };
        this.dcLoading = true;
        getExport(params).then((res) => {
          this.dcLoading = false;
          this.$utils.downloadFileFun(res, "字典管理.xls");
        });
      }
    },
    // 是否启用
    handleSwitch(row) {
      updateDictStatus({
        id: row.id,
        status: row.status,
      }).then((res) => {
        if (res.code === 200) {
          this.getData();
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 数据项
    handleDataItem(row) {
      this.currentRow = row;
      this.isShow = true;
    },
    handleRefreshChange() {
      this.isShow = false;
    },
    // 新增、编辑--保存
    handleSubmit() {
      this.$refs["drawerForm"].validate((valid) => {
        if (/[\u4e00-\u9fa5]+/.test(this.drawerForm.code)) {
          this.$message.warning("字典编码不能包含中文");
          return;
        }
        if (valid) {
          const param = {
            ...this.drawerForm,
          };
          if (this.btnType === 2) {
            // 编辑
            param.id = this.currentRow?.id;
          }
          this.qrLoading = true;
          saveOrUpdateDict(param).then((res) => {
            this.qrLoading = false;
            if (res.code === 200) {
              this.getData();
              this.showDrawer = false;
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleExport() {},
    // 导入
    handlechange(file, fileList) {
      // 导入
      const fileType = file.name.substr(file.name.lastIndexOf(".")).trim();
      if (fileType !== ".xlsx" && fileType !== ".xls") {
        this.$message.warning("请选择Excel格式的文件导入！");
        return;
      }
      const formData = new FormData();
      formData.append("file", file.raw);
      this.drLoading = true;
      importExcel(formData).then((res) => {
        this.drLoading = false;
        const blob = new Blob([res]);
        if (blob.size === 0) {
          this.getData();
          this.$message.success("导入成功");
        } else {
          this.$utils.downloadFileFun(res, "字典管理.xls");
        }
      });
    },
    // 查询
    handleSearch(value) {
      this.newCondition = value;
      this.currentPage = 1;
      this.getData();
    },
    // 重置
    handleReset(val) {
      this.handleSearch(val);
    },
    // 编辑
    handleEdit(row) {
      this.currentRow = row;
      this.btnType = 2;
      this.title = "编辑字典";
      this.handleSetForm(row);
      this.showDrawer = true;
    },
    handleSetForm(row) {
      this.$handleSetForm(this.drawerForm, 1, row);
    },
    // 删除
    handleDelete(row) {
      this.$ckConfirm({
        content: "此操作将删除该条记录，并无法恢复， 是否继续?",
        title: "提示",
        okFn: (res) => {
          deleteDict({
            id: row.id,
          }).then((res) => {
            if (res.code === 200) {
              this.currentPage = 1;
              this.getData();
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          });
        },
        cancelFn: (res) => {
          console.log("取消");
        },
      });
    },
    // 新增
    handleAdd() {
      this.btnType = 1;
      this.title = "新增字典";
      this.$handleSetForm(this.drawerForm, 0);
      this.drawerForm.status = "1";
      this.showDrawer = true;
    },
    // 分页数据
    getData() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        status: this.newCondition.status,
        nameOrCode: this.newCondition.nameOrCode,
      };
      this.tableLoading = true;
      listSysDictByPage(params)
        .then(res => {
          this.tableLoading = false;
          if (res.code === 200) {
            this.tableData = res.data.records;
            this.total = res.data.total;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    // 分页
    pageChange(payload) {
      this.currentPage = payload.current;
      this.pageSize = payload.pageSize;
      this.getData();
    },
  },
};
</script>
<style lang="less" scoped>
.wraper {
  display: flex;
  height: 100%;
  overflow: hidden;
}
.buttons {
  margin: 0px 5px;
  height: 27px;
  margin-top: -1px;
}
</style>
